package com.zmn.oms.services.impl.EnterpriseWeChat;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.model.entity.enterpriseWeChat.EnterpriseWeChatLog;
import com.zmn.oms.model.entity.wechatwork.OmsOrderWechatWorkLog;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import com.zmn.oms.services.interfaces.enterpriseWeChat.EnterpriseWeChatService;
import com.zmn.oms.services.interfaces.wechatwork.OmsOrderWechatWorkLogService;
import com.zmn.ums.common.dro.weixincp.WeixincpExternalUserDRO;
import com.zmn.ums.dubbo.interfaces.weixincp.WeixincpUserListRemoteService;
import com.zmn.ums.dubbo.interfaces.weixincp.WeixincpUserModifyRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：企业微信
 *
 * @author hgb
 * @date 2020年07月07日18:35:10
 */
@Slf4j
@Service
public class EnterpriseWeChatServiceImpl implements EnterpriseWeChatService {
    @Autowired
    private EnterpriseWeChatService enterpriseWeChatService;
    @Autowired
    private OrderWorkListBService orderWorkListBService;
    @Autowired
    private ElasticSearchDataSyncService elasticSearchDataSyncService;
    @Autowired
    private OmsOrderWechatWorkLogService omsOrderWechatWorkLogService;

    @Reference(version = com.zmn.ums.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private WeixincpUserListRemoteService weixincpUserListRemoteService;
    @Reference(version = com.zmn.ums.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private WeixincpUserModifyRemoteService weixincpUserModifyRemoteService;

    @Override
    public void syncByVisitUserId(long visitUserId) {
        if (NumberUtil.isNullOrZero(visitUserId)) {
            return;
        }
        log.info("绑定企业微信1==>{}", visitUserId);

        // 查询同步 预约时间是当天
        OrderWorkQuery orderWorkQuery = new OrderWorkQuery();
        orderWorkQuery.setVisitUserId(visitUserId);
        orderWorkQuery.setPageSize(OrderConsts.MAX_QUERY_ORDER_SIZE);
        orderWorkQuery.setIncludes(Lists.newArrayList("orderId", "id"));
        String nowDate = DateUtil.getNowFormatted("yyyy-MM-dd");
        orderWorkQuery.setLastVisitScanTime(nowDate + " 00:00:00," + nowDate + " 23:59:59");
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(orderWorkQuery);
        if (CollectionUtils.isEmpty(esOrderWorkList)) {
            return;
        }

        log.info("绑定企业微信2==>{}", esOrderWorkList);
        List<Long> orderIdList = esOrderWorkList.stream().map(EsOrderWork::getOrderId).collect(Collectors.toList());
        List<List<Long>> partition = Lists.partition(orderIdList, 500);
        partition.forEach(e -> {
            weixincpUserModifyRemoteService.saveWeixincpUserOrder(e, visitUserId);
            elasticSearchDataSyncService.syncWorkIndex(e);
        });

        log.info("绑定企业微信3==>{}", orderIdList);
        // 添加企业微信关系日志
        ResponseDTO<WeixincpExternalUserDRO> externalUserDRO = weixincpUserListRemoteService.getExternalUserByZmnUserId(visitUserId);
        log.info("-----syncByVisitUserId------获取企业微信联系人信息externalUserDRO={} visitUserId={}", externalUserDRO, visitUserId);
        if (externalUserDRO.getData() != null) {
            WeixincpExternalUserDRO externalUser = externalUserDRO.getData();
            Date date = externalUser.getCreateTime() != null ? DateUtil.parse(externalUser.getCreateTime()) : DateUtil.getNow();
            esOrderWorkList.forEach(x -> {
                EnterpriseWeChatLog weChatLog = new EnterpriseWeChatLog();
                weChatLog.setAddTime(date);
                weChatLog.setNickname(externalUser.getName());
                weChatLog.setOperatingTime(DateUtil.getNow());
                weChatLog.setWorkId(x.getId());
                weChatLog.setZmnUserId(externalUser.getZmnUserId());
                weChatLog.setOrderId(x.getOrderId());
                weChatLog.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
                weChatLog.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
                log.info("绑定企业微信4==>{}", weChatLog);
                enterpriseWeChatService.addEnterpriseWeChatLog(weChatLog);
            });

        }
    }

    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_ENTERPRISE_WX_LOG)
    public void addEnterpriseWeChatLog(EnterpriseWeChatLog enterpriseWeChatLog) {
        if (Objects.isNull(enterpriseWeChatLog)) {
            return;
        }
        Date now = DateUtil.getNow();
        OmsOrderWechatWorkLog wechatWorkLog = new OmsOrderWechatWorkLog();
        BeanUtil.copyProperties(enterpriseWeChatLog, wechatWorkLog);
        wechatWorkLog.setNickName(enterpriseWeChatLog.getNickname());
        wechatWorkLog.setZmnUserId(enterpriseWeChatLog.getZmnUserId());
        wechatWorkLog.setCreateTime(now);
        wechatWorkLog.setUpdateTime(now);
        omsOrderWechatWorkLogService.insert(wechatWorkLog);
    }

}
